import WebSocket from 'ws';

export default class MessageHandler {
  private heartbeatInterval?: NodeJS.Timeout;
  private heartbeatIntervalMs: number = 5000; // 默认5秒心跳间隔

  // 处理所有收到的消息
  processMessage(msg: WebSocket.Data, source: 'client' | 'server', connection?: WebSocket) {
    try {
      const messageStr = msg.toString();

      // 尝试解析JSON（OneBot协议使用JSON格式）
      const message = JSON.parse(messageStr);

      // 如果是心跳回应，特殊处理
      if (message?.post_type === 'meta_event') {
        if (message?.meta_event_type === 'heartbeat') {
          console.log(`[${source}] 收到心跳回应:${messageStr}`);
          return;
        }
        if (message?.meta_event_type === 'lifecycle') {
          console.log(`[${source}] 生命周期:${messageStr}`);
          return;
        }
      }
      if(message?.post_type === 'message') {
        console.log(`[${source}] 收到消息:${messageStr}`);
        return;
      }

      console.log(`[${source === 'client' ? 'WS Client' : 'WS Server'}] 收到原始消息: ${messageStr}`);

      // 其他消息处理逻辑...
      // if (connection && connection.readyState === WebSocket.OPEN) {
      //   connection.send(JSON.stringify({ echo: message }));
      // }

    } catch (e) {
      console.error(`[${source}] 消息解析失败:`, e);
    }
  }

  // 连接成功时的处理
  onConnected(source: 'client' | 'server', url: string, connection?: WebSocket) {
    console.log(`[${source === 'client' ? 'WS Client' : 'WS Server'}] 已连接到 ${url}`);

    // 如果是服务端连接，启动心跳定时器
    if (source === 'server' && connection) {
      this.startHeartbeat(connection);
    }
  }

  // 启动心跳检测
  private startHeartbeat(connection: WebSocket) {
    this.stopHeartbeat(); // 先停止已有的心跳

    this.heartbeatInterval = setInterval(() => {
      if (connection.readyState === WebSocket.OPEN) {
        const heartbeatMsg = {
          post_type: 'meta_event',
          meta_event_type: 'heartbeat',
          time: Math.floor(Date.now() / 1000), // Unix时间戳
          self_id: 12345, // 替换为你的机器人ID
          interval: this.heartbeatIntervalMs
        };

        connection.send(JSON.stringify(heartbeatMsg));
        console.log('[WS Server] 发送心跳包');
      }
    }, this.heartbeatIntervalMs);
  }

  // 停止心跳检测
  private stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
      this.heartbeatInterval = undefined;
    }
  }

  // 连接关闭时的清理
  onDisconnected() {
    this.stopHeartbeat();
  }
}